/**
 * JAVACC DEMO 1.0
 * @copy right zbxsoft company All rights reserved. 
 */
package ${packPath}.controller;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zbx.database.model.Page;
import com.zbxsoft.api.entity.BaseEntity;
import com.zbxsoft.api.vo.ParamsVo;
import com.zbxsoft.api.vo.ResultMsg;
import com.zbxsoft.api.vo.Token;
import com.zbxsoft.cache.util.Validator;
import com.zbxsoft.tools.StrUtil;
import com.zbxsoft.uct.common.BaseAction;
import com.zbxsoft.uct.common.LoginUser;
import com.zbxsoft.uct.common.PBOSSOTools;
import com.zbxsoft.uct.common.entity.User;
import ${packPath}.manager.UnityBaseManager;

/**
 * description:  系统统一父action类
 * @Copyright(c)2014:北京中百信软件技术有限公司
 */
public abstract class UnitySupperAction<T extends BaseEntity> extends BaseAction<T> {

	protected abstract UnityBaseManager<T> getBaseManager();

	protected abstract String getCommBoxValue(T item, String type);

	/**
	 *查询列表分页数据，返回JSON数据
	 */
	@RequestMapping(value = { "/rfs" })
	@ResponseBody
	protected Object listData(HttpServletRequest request, @ModelAttribute T item, String page, String rows) {
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setObj(item);
		Map<String, Object> mapData = new HashMap<String, Object>();
		if (Validator.isNotNull(rows)) {//rows为空表示不进行分页处理
			vo.setParams("pageSize", Validator.getDefaultStr(rows, "10"));
			vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
			Page pageList = getBaseManager().getPageInfo(vo);//分页
			mapData.put("total", pageList.getCount());//dataGrid所需参数
			mapData.put("rows", pageList.getPageObjects());//dataGrid所需数据对象集合
		} else {
			List<T> list = getBaseManager().getList(vo);
			if (!Validator.isEmpty(list)) {
				mapData.put("total", list.size());//dataGrid所需参数
				mapData.put("rows", list);//dataGrid所需数据对象集合
			}
		}
		return mapData;
	}

	/**
	 *查询单个对象，返回JSON数据
	 */
	@RequestMapping(value = { "/rf/{id}" }, method = { RequestMethod.GET })
	@ResponseBody
	protected Object infoData(@PathVariable String id, HttpServletRequest request) {
		Map<String, Object> mapData = new HashMap<String, Object>();
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setInfoId(id);
		mapData.put("flag", "T");
		mapData.put("msg", "查询成功！");
		mapData.put("item", getBaseManager().getInfoById(vo));
		return mapData;
	}

	@RequestMapping(value = { "/to/{id}" }, method = { RequestMethod.GET })
	protected ModelAndView toView(@PathVariable String id, HttpServletRequest request) {
		ModelAndView view = new ModelAndView(getPrefix() + "view");
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setInfoId(id);
		view.addObject("item", getBaseManager().getInfoById(vo));
		return view;
	}

	@RequestMapping(value = { "/to/{id}/{jspName}" }, method = { RequestMethod.GET })
	protected ModelAndView toView(@PathVariable String id, @PathVariable String jspName, HttpServletRequest request) {
		ModelAndView view = new ModelAndView(getPrefix() + jspName);
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setInfoId(id);
		view.addObject("item", getBaseManager().getInfoById(vo));
		return view;
	}

	@RequestMapping(value = { "/to/{id}/{folder}/{jspName}" }, method = { RequestMethod.GET })
	protected ModelAndView toView(@PathVariable String id, @PathVariable String folder, @PathVariable String jspName,
			HttpServletRequest request) {
		ModelAndView view = new ModelAndView(folder + "/" + jspName);
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setInfoId(id);
		view.addObject("item", getBaseManager().getInfoById(vo));
		return view;
	}

	@RequestMapping(value = { "/to/{id}/{folder1}/{folder2}/{jspName}" }, method = { RequestMethod.GET })
	protected ModelAndView toView(@PathVariable String id, @PathVariable String folder1, @PathVariable String folder2,
			@PathVariable String jspName, HttpServletRequest request) {
		ModelAndView view = new ModelAndView(folder1 + "/" + folder2 + "/" + jspName);
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setInfoId(id);
		view.addObject("item", getBaseManager().getInfoById(vo));
		return view;
	}

	/**
	 * 保存信息（带token)
	 */
	@Token(remove = true)
	@RequestMapping(value = { "/rf" }, method = { RequestMethod.POST })
	@ResponseBody
	public ResultMsg saveInfo(HttpServletRequest request, HttpServletResponse response, @ModelAttribute T item) {
		ResultMsg rmsg = null;//用于封装结果信息
		response.setContentType("text/html");

		ParamsVo<T> vo = this.getParamsVo(request);//初始化参数vo对象，如果是登陆用户则获取用户信息及日志
		vo.setParams("loginUser", PBOSSOTools.getLoginUser(request));//存放当前登录用户
		vo.setObj(item);//新增
		String id = getBaseManager().saveInfo(vo);
		if (Validator.isNull(id)) {
			rmsg = this.getResultMsg(request, "新增条目失败，请重试!");
		} else {
			rmsg = new ResultMsg("T", id);
		}
		return rmsg;
	}

	/**
	 * 修改信息（带token)
	 */
	@Token(remove = true)
	@RequestMapping(value = { "/rf/{id}" }, method = { RequestMethod.PUT })
	@ResponseBody
	public ResultMsg editInfo(HttpServletRequest request, HttpServletResponse response, @ModelAttribute T item,
			@PathVariable String id) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		if (Validator.isNull(id)) {
			rmsg = new ResultMsg("F", "请选择要修改的信息！");
			return rmsg;
		}
		ParamsVo<T> vo = this.getParamsVo(request);//初始化参数vo对象，如果是登陆用户则获取用户信息及日志
		vo.setObj(item);//修改
		boolean mark = getBaseManager().editInfo(vo);
		if (!mark) {
			rmsg = this.getResultMsg(request, "操作失败！");
		}
		return rmsg;
	}

	/**
	 * 根据id删除session表信息
	 */
	@RequestMapping(value = { "/rf/{id}" }, method = { RequestMethod.DELETE })
	@ResponseBody
	public ResultMsg deleteInfo(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
		//初始化结果提示信息
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");
		response.setContentType("text/html");
		if (Validator.isNull(id)) {
			rmsg = new ResultMsg("F", "缺少必要的参数!");
			return rmsg;
		}
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setInfoId(id);
		vo.setParams("isDelete", "true");
		boolean mark = getBaseManager().deleteInfo(vo);
		if (!mark) {
			rmsg = new ResultMsg("F", "操作失败！");
		}
		return rmsg;
	}

	@RequestMapping(value = { "/select" }, method = { RequestMethod.POST })
	@ResponseBody
	public JSONArray selectData(HttpServletRequest request, T item) {
		ParamsVo<T> vo = this.getParamsVo(request);//初始化参数vo对象，如果是登陆用户则获取用户信息及日志
		vo.setObj(item);//新增
		List<T> list = getBaseManager().getList(vo);
		JSONArray jary = new JSONArray();
		//		JSONObject nvo = new JSONObject();
		//		nvo.put("id", "");
		//		nvo.put("text", "--请选择--");
		//		jary.add(nvo);
		if (!Validator.isEmpty(list)) {
			for (T obj : list) {
				JSONObject jvo = new JSONObject();
				jvo.put("id", getCommBoxValue(obj, "id"));
				jvo.put("text", getCommBoxValue(obj, "text"));
				jary.add(jvo);
			}
		}
		return jary;
	}

	@RequestMapping("toList")
	protected ModelAndView toList(HttpServletRequest request, @ModelAttribute T item, String page, String rows) {
		ModelAndView view = new ModelAndView(getPrefix() + "lists");
		//取列表
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setObj(item);
		vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
		vo.setParams("pageSize", Validator.getDefaultStr(rows, "10"));
		Page pageList = getBaseManager().getPageInfo(vo);//分页
		view.addObject("list", pageList.getPageObjects());
		view.addObject("page", Validator.getDefaultStr(page, "1"));
		view.addObject("rows", Validator.getDefaultStr(rows, "10"));
		view.addObject("total", pageList.getCount());
		view.addObject("item", item);
		return view;
	}

	@RequestMapping("toList/{jspName}")
	protected ModelAndView toList(HttpServletRequest request, @ModelAttribute T item, @PathVariable String jspName,
			String page, String rows) {
		ModelAndView view = new ModelAndView(getPrefix() + jspName);
		//取列表
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setObj(item);
		vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
		vo.setParams("pageSize", Validator.getDefaultStr(rows, "10"));
		Page pageList = getBaseManager().getPageInfo(vo);//分页
		view.addObject("list", pageList.getPageObjects());
		view.addObject("page", Validator.getDefaultStr(page, "1"));
		view.addObject("rows", Validator.getDefaultStr(rows, "10"));
		view.addObject("total", pageList.getCount());
		view.addObject("item", item);
		return view;
	}

	protected ResultMsg getResultMsg(HttpServletRequest request, String msg) {
		request.getSession().setAttribute("formToken", request.getAttribute("formToken"));
		ResultMsg rmsg = new ResultMsg("F", msg);
		return rmsg;
	}

	protected User getSessionUser(HttpServletRequest request) {
		LoginUser loginUser = PBOSSOTools.getLoginUser(request);
		if (!Validator.isEmpty(loginUser)) {
			return loginUser.getUser();
		}
		return null;
	}

	/**
	 * description:  日志生成调用方法
	 * @param request
	 */
	protected ParamsVo<T> getParamsVo(HttpServletRequest request) {
		ParamsVo<T> params = new ParamsVo<T>();
		params.setParams("logIp", getUserIp(request));
		params.setLogClassName(getGenType().trim());
		User user = getSessionUser(request);
		if (null == user)
			return params;
		params.setUserEname(user.getUserEname());
		params.setUserId(user.getUserId());
		return params;
	}

	/**
	 * description:  获取访问IP
	 * @param request 当前请求
	 * @return   
	 * @author Hou Dayu  
	 */
	protected String getUserIp(HttpServletRequest request) {
		String ip = "";
		try {
			ip = request.getHeader("x-forwarded-for");
			if (Validator.isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (Validator.isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (Validator.isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			if (Validator.isNotNull(ip) && ip.length() > 32) {
				ip = ip.substring(0, 32);
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return ip;
	}

	protected String getGenType() {
		Type genType = getClass().getGenericSuperclass();
		Type[] ddd = ((ParameterizedType) genType).getActualTypeArguments();
		String className = ddd[0].toString().replaceAll("class", "");
		return className.toString();
	}

	@SuppressWarnings({ "rawtypes" })
	protected Map<String, String> getParameterMap(HttpServletRequest request) {
		Map<String, String> data = new HashMap<String, String>();
		Set keSet = request.getParameterMap().entrySet();
		for (Iterator itr = keSet.iterator(); itr.hasNext();) {
			Map.Entry me = (Map.Entry) itr.next();
			String ok = String.valueOf(me.getKey());
			Object ov = me.getValue();
			String value = "";
			if ((ov instanceof String[])) {
				String[] vls = (String[]) ov;
				value = vls[0];
			} else {
				value = String.valueOf(ov);
			}
			if (StrUtil.isNotNull(value)) {
				try {
					if (value.equals(new String(value.getBytes("iso8859-1"), "iso8859-1"))) {
						value = new String(value.getBytes("iso8859-1"), "utf-8");
					}
				} catch (IOException e) {
				}
				data.put(ok, value);
			}
		}
		return data;
	}
}
